package fr.emse.tsc;

import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

import android.util.Log;

public class Connexion {
	
	private String server = null;
	private int port = 0;
	private Socket socket = null;
	private boolean connected = false;
	private PrintWriter out = null;
	private BufferedReader in = null;
	
	public Connexion() {
		this.server = null;
		this.port = 0;
	}

	public boolean connect(String server, int port, String name) throws IOException {
		this.server = server;
		this.port = port;
		InetAddress serverAddr = InetAddress.getByName(server);
		socket = new Socket(serverAddr, port);
		String message = "HELO " + name;
		out = new PrintWriter( new BufferedWriter( new OutputStreamWriter(socket.getOutputStream())),true);
		out.print(message);
		out.flush();
		in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
		String reponse = in.readLine();
		if (reponse.equals("OK")) {
			connected = true;
		}
        else {
        	Log.d("TSC", "Connect: server says " + reponse);
            disconnect();
          	connected = false;
        }
		return connected;
	}
	
	public String sendMessage(String message) throws IOException {
		String reponse = null;
		if (connected) {
			out.print(message);
			out.flush();
			reponse = in.readLine();
			return reponse;
		}
		else throw new IOException("Not connected");
	}
	
	public String getServer() {
		return server;
	}

	public int getPort() {
		return port;
	}

	public Socket getSocket() {
		return socket;
	}

	public boolean isConnected() {
		return connected;
	}
	
	public void disconnect() throws IOException {
		if (connected) {
			out.print("QUIT");
			out.flush();
			String reponse = in.readLine();
			if (reponse.equals("OK") == false) {
				Log.i("TSC", "Disconnect warning");
			}
			connected = false;
			out.close();    out    = null;
			in.close();     in     = null;
			socket.close();	socket = null;
		}
	}
}
